package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.mapper.FavoriteBusinessMapper;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.service.FavoriteBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FavoriteBusinessServiceImpl implements FavoriteBusinessService {

    @Autowired
    private FavoriteBusinessMapper favoriteBusinessMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public void addFavorite(String userId, String businessId) {
        if (userId == null || businessId == null) {
            throw new RuntimeException("用户ID或商家ID不能为空");
        }
        // 校验商家是否存在
        Business business = businessMapper.getBusinessById(businessId);
        if (business == null) {
            throw new RuntimeException("商家不存在");
        }
        // 已存在则忽略
        if (favoriteBusinessMapper.exists(userId, businessId) > 0) {
            return;
        }
        int result = favoriteBusinessMapper.addFavorite(userId, businessId);
        if (result <= 0) {
            throw new RuntimeException("添加收藏失败");
        }
    }

    @Override
    public void removeFavorite(String userId, String businessId) {
        if (userId == null || businessId == null) {
            throw new RuntimeException("用户ID或商家ID不能为空");
        }
        favoriteBusinessMapper.removeFavorite(userId, businessId);
    }

    @Override
    public boolean isFavorite(String userId, String businessId) {
        if (userId == null || businessId == null) {
            return false;
        }
        return favoriteBusinessMapper.exists(userId, businessId) > 0;
    }

    @Override
    public List<Business> getUserFavorites(String userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return favoriteBusinessMapper.listFavoritesByUserId(userId);
    }
}
